package com.lubase.core.service.flowform.impl;

import com.alibaba.fastjson.JSON;
import com.lubase.core.service.flowform.model.CustomPageSetting;
import com.lubase.core.service.flowform.model.PageDataWFExtendModel;
import com.lubase.model.DbEntity;
import com.lubase.orm.exception.WarnCommonException;
import com.lubase.orm.model.DbCollection;
import com.lubase.orm.service.DataAccess;
import com.lubase.orm.util.TypeConverterUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Slf4j
@Component
public class PageJumpUtil {

    @Autowired
    DataAccess dataAccess;

    public PageDataWFExtendModel getServiceId(DbEntity button, DbEntity pageEntity) {
        String settingStr = "";
        if (button.containsKey("server_setting") && !StringUtils.isEmpty(button.get("server_setting"))) {
            settingStr = TypeConverterUtils.object2String(button.get("server_setting"));
        } else if (pageEntity.containsKey("workflow_setting")) {
            settingStr = TypeConverterUtils.object2String(pageEntity.get("workflow_setting"));
        }
        PageDataWFExtendModel dataWFExtendModel = null;
        if (!StringUtils.isEmpty(settingStr)) {
            try {
                dataWFExtendModel = JSON.parseObject(settingStr, PageDataWFExtendModel.class);
            } catch (Exception exception) {
                log.error("workflow_setting配置格式不正确:" + pageEntity.getId() + settingStr, exception);
            }
        }
        return dataWFExtendModel;
    }

    @SneakyThrows
    public CustomPageSetting getRefPageSetting(String oInsId, String userId) {
        if (StringUtils.isEmpty(oInsId)) {
            return null;
        }
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        DbCollection collOIns = dataAccess.queryById("wf_oins", Long.parseLong(oInsId));
        if (collOIns.getData().isEmpty()) {
            throw new WarnCommonException("未找到待办处理数据");
        }
        String taskId = collOIns.getData().get(0).get("task_id").toString();

        DbCollection collTask = dataAccess.queryById("wf_task", Long.parseLong(taskId));
        if (collTask.getData().isEmpty()) {
            throw new WarnCommonException("流程配置错误，当前节点已经被删除");
        }
        DbEntity taskEntity = collTask.getData().get(0);
        String taskSetting = TypeConverterUtils.object2String(taskEntity.get("ref_page_setting"), "");
        if (StringUtils.isEmpty(taskSetting)) {
            return null;
        }
        CustomPageSetting pageSetting = null;
        try {
            pageSetting = JSON.parseObject(taskSetting, CustomPageSetting.class);
        } catch (Exception exception) {
            log.error(String.format("任务节点%s转换taskSettingModel失败", taskEntity.getId()), exception);
        }
        return pageSetting;
    }
}
